import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import * as bcrypt from 'bcryptjs';
import { LoginDto } from './dto/login.dto';

@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name);

  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    try {
      const user = await this.usersService.findByUsername(username);
      this.logger.log(`用户 ${username} 存在，正在验证密码`);
      
      const isPasswordValid = await bcrypt.compare(password, user.password);
      
      if (isPasswordValid) {
        this.logger.log(`用户 ${username} 密码验证成功`);
        const { password, ...result } = user;
        return result;
      } else {
        this.logger.warn(`用户 ${username} 密码验证失败`);
        return null;
      }
    } catch (error) {
      this.logger.error(`验证用户 ${username} 时出错: ${error.message}`);
      return null;
    }
  }

  async login(loginDto: LoginDto) {
    const { username, password } = loginDto;
    this.logger.log(`尝试登录用户: ${username}`);
    
    const user = await this.validateUser(username, password);

    if (!user) {
      this.logger.warn(`用户 ${username} 登录失败`);
      throw new UnauthorizedException('用户名或密码不正确');
    }

    const payload = { username: user.username, sub: user.id };
    this.logger.log(`用户 ${username} 登录成功，生成令牌`);

    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
      },
    };
  }
}
